#include <am.h>
#include <klib.h>
#include <klib-macros.h>

#define IP_BASE_ADDR 0x10004000
#define REG_CTRL1 *((volatile uint32_t *)(IP_BASE_ADDR + 0))
#define REG_CTRL2 *((volatile uint32_t *)(IP_BASE_ADDR + 4))
#define REG_DIV   *((volatile uint32_t *)(IP_BASE_ADDR + 8))
#define REG_CAL   *((volatile uint32_t *)(IP_BASE_ADDR + 12))
#define REG_TRL   *((volatile uint32_t *)(IP_BASE_ADDR + 16))
#define REG_TXR   *((volatile uint32_t *)(IP_BASE_ADDR + 20))
#define REG_RXR   *((volatile uint32_t *)(IP_BASE_ADDR + 24))
#define REG_STAT  *((volatile uint32_t *)(IP_BASE_ADDR + 28))

int main(){
    putstr("spi nor flash test\n");

    REG_DIV = (uint32_t)0;
    REG_CTRL1 = (uint32_t)0x8;
    REG_CTRL2 = (uint32_t)0x20;
    REG_CTRL2 = (uint32_t)0x24;

    REG_TXR = (uint32_t)0x06;
    REG_CTRL2 = (uint32_t)0x2C;

    REG_CTRL1 = (uint32_t)0x3C8;
    REG_TXR = (uint32_t)0x02000000;
    for(int i = 0; i < 6; ++i) {
        REG_TXR = i;
    }
    REG_CAL = (uint32_t)0;
    REG_TRL = (uint32_t) (6 + 1);
    REG_CTRL2 = (uint32_t)0x2C;

    while(((REG_STAT & 0x04) >>2)== 1);

    REG_TXR = (uint32_t)0x03000000;
    REG_CAL = (uint32_t)6;
    REG_TRL = (uint32_t)(6+1);
    REG_CTRL2 = (uint32_t)0x3C;

    uint32_t recv_val;
    for(int i = 0; i < 6; ++i) {
        while(((REG_STAT & 0x10) >> 4)== 1);
        recv_val = REG_RXR;
        if(recv_val != i) putstr("err match\n");
    }

    putstr("test done\n");

    return 0;
}
